import ctypes
import os
import subprocess
import time
import winreg
import traceback
import click
import win32profile
import win32con
import win32security

def check_admin():
    """验证管理员权限"""
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False


def get_kiosk_sid(username):
    """获取指定用户的 SID"""
    try:
        cmd = f'wmic useraccount where name="{username}" get sid'
        result = subprocess.run(cmd, capture_output=True, text=True, shell=True)
        sid_lines = [line.strip() for line in result.stdout.split('\n') if line.strip()]
        if len(sid_lines) > 1:
            return sid_lines[1]
        return None
    except Exception as e:
        click.echo(f"获取 SID失败: {e}", err=True)
        return None


def set_registry_config(username, password, sid, chrome_path, url, kiosk=False,
                        autologin=False):
    """配置特定用户注册表实现全屏启动"""
    try:
        # 登录用户, 确保注册表项是存在的, 否则在CreateKey处会报错
        token = win32security.LogonUser(username, None, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT)
        profile = win32profile.LoadUserProfile(token, {'UserName': username})
        sid = win32security.ConvertSidToStringSid(win32security.GetTokenInformation(token, win32security.TokenUser)[0])
        user_winlogon_path = rf"{sid}\Software\Microsoft\Windows NT\CurrentVersion\Winlogon"
        key = winreg.CreateKey(winreg.HKEY_USERS, user_winlogon_path)
        model = '--kiosk' if kiosk else '--start-fullscreen'
        params = f"{chrome_path} {model} {url} --disable-extensions --process-per-site"
        winreg.SetValueEx(key, "Shell", 0, winreg.REG_SZ, params)
        winreg.CloseKey(key)

        # 系统级功耗 optimization
        # power_key = winreg.CreateKey(winreg.HKEYLOCALMACHINE, "SYSTEM\CurrentControlSet\Control\Session Manager\Power")
        # winreg.SetValue(power_key, "HiberbootEnabled", winreg.REGDWORD, 0)
        # winreg.CloseKey(power_key)

        # Winlogon配置, 确保本机器启动方式仍然为文件管理器
        win_logon_key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE,
                                         r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon")
        winreg.SetValueEx(win_logon_key, "Shell", 0, winreg.REG_SZ, "explorer.exe")
        if autologin:
            winreg.SetValueEx(win_logon_key, "AutoAdminLogon", 0, winreg.REG_SZ, "1")
            winreg.SetValueEx(win_logon_key, "DefaultUserName", 0, winreg.REG_SZ, username)
            winreg.SetValueEx(win_logon_key, "DefaultPassword", 0, winreg.REG_SZ, password)
        else:
            winreg.DeleteValue(win_logon_key, "AutoAdminLogon")
            winreg.DeleteValue(win_logon_key, "DefaultUserName")
            winreg.DeleteValue(win_logon_key, "DefaultPassword")
            # 域名设置, 如果是本地账户，不需要添加
            # winreg.SetValueEx(win_logon_key, "DefaultDomainName",0,  winreg.REG_SZ, '')
        winreg.CloseKey(win_logon_key)

        return True
    except Exception as e:
        click.echo(f"注册表设置失败: {e}", err=True)
        traceback.print_exc()
        return False


DEFAULT_CHROME_PATH = r"C:\Program Files\Google\Chrome\Application\chrome.exe"


@click.command()
@click.option('--user', '-u', help="用户名")
@click.option('--password', '-p', help="密码")
@click.option('--autologin/--no-autologin', help="是否自动登录")
@click.option('--url', help="指定需要展示的网址")
@click.option('--kiosk/--full-screen', help="开启kiosk模式, 默认为False, 对应普通全屏模式")
@click.option('--chrome-path', '-cp', type=click.Path(),
              default=DEFAULT_CHROME_PATH,
              help="chrome安装位置")
def main(user, password, autologin, url, kiosk, chrome_path):
    if not check_admin():
        click.echo("请以管理员身份运行本程序")

    if not user:
        user = click.prompt('请输入用户名')
    if not autologin:
        autologin = click.prompt('是否自动登录', default=False, type=bool)
    if password is None:
        password = click.prompt('请输入密码', hide_input=True)

    sid = get_kiosk_sid(user)
    if not sid:
        click.echo(f"未找到名为{user}用户的SID", err=True)
        raise OSError(f"未找到名为{user}用户的SID")
    click.echo(f"找到名为{user}用户的SID: {sid}")

    chrome_path = chrome_path if os.path.exists(chrome_path) else r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
    if not chrome_path or not os.path.exists(chrome_path):
        click.echo(f"⚠️指定的Chrome程序不存在：{chrome_path}")
        chrome_path = click.prompt('请手动输入Chrome程序路径', type=click.Path(exists=True))

    if not url:
        url = click.prompt('请输入指定网址')
    if kiosk is None:
        kiosk = click.prompt('是否开启独占模式', default=False, type=bool)
    click.echo(f"""
用户名: {user}
SID: {sid}
自动登录: {autologin}
Chrome程序路径: {chrome_path}
URL: {url}
kiosk模式: {kiosk}
""")
    time.sleep(10)
    success = set_registry_config(user, password, sid, chrome_path, url, kiosk, autologin)
    if success:
        click.echo("\n配置成功！建议重启系统使设置生效")
    else:
        click.echo("\n部分配置失败，请检查错误信息")


if __name__ == '__main__':
    main()
